
const model = require('../schems')


let blogAction={}

//获得简略描述
function dec(str){
  var str1 = str.replace(/\s/g,'') //去空格
  var str2 = str1.replace(/<\/?.+?>/g,""); //去标签
  var str3 = str2.replace(/!\[\]\((.*?)\)/g,'') //去图片
  var str4 = str3.replace(/[\\\`\*\_\[\]\#\+\-\!\>]/g,'') //去掉markdown标签
  var str5 =str4.substring(0,200)
  return str5
}

//点击排行
blogAction.clickRank =  function(){
  return new Promise(function(resolve,reject){
 model.article.find({'state':1}).populate('categoryId', 'cateid').limit(10).select({title:1,_id:1}).sort({'countInfo.visitCount':-1}).exec(function(err,doc){

  resolve(JSON.parse(JSON.stringify(doc)))
 })
})
}

//推荐排行
blogAction.topRank = function(){
  return new Promise(function(resolve,reject){
    let tuijian;
    model.article.find({'state':1,'top':true}).populate('categoryId', 'cateid').limit(10).select({title:1,_id:1}).sort({updateAt:-1}).exec(function(err,doc){
      if(doc){
        tuijian = doc
      }else{
        tuijian =[]
      }
      resolve(JSON.parse(JSON.stringify(tuijian)))
      //console.log('推荐',tuijian)
    })
  })
}

//最近更新
blogAction.newUP = function(){
  return new Promise(function(resolve,reject){
    let newlist;
    model.article.find({'state':1}).populate('categoryId', 'cateid').limit(10).select({title:1,_id:1}).sort({updateAt:-1}).exec(function(err,doc){
      if(doc){
        newlist = doc
      }else{
        newlist =[]
      }
      //console.log('最近更新',newlist)
      resolve(JSON.parse(JSON.stringify(newlist)))
    })
  })
}

//图文
blogAction.pic = function(){
  return new Promise(function(resolve,reject){
    let newlist;
    model.article.find({'state':1,'thumbnail':{$ne:''}}).populate('categoryId', 'cateid').limit(6).select({title:1,_id:1,thumbnail:1}).sort({updateAt:1}).exec(function(err,doc){
      if(doc){
        newlist = doc
      }else{
        newlist =[]
      }
      resolve(JSON.parse(JSON.stringify(newlist)))
    })
  })
}


//根据id查询文章
blogAction.blogById =  function (_id) {
  return new Promise(function(resolve,reject){
    model.article.findOne({_id}).populate('authorId', 'name').exec(function(err,doc){
      resolve(JSON.parse(JSON.stringify(doc)))
   })
  })
}

//分类文章
blogAction.blogByCate =  function (cateid,page) {
  let data = {}
  let min= (page-1)*10;


  return new Promise(async function(resolve,reject){
    let categoryId
    await model.category.findOne({cateid},function(err,result){
      //console.log('objectid',result)
       categoryId = result._id
     })
     //分页
     await model.article.find({'state':1,categoryId}).count({}, (err, count) => {
      data.count=count
   })

     await model.article.find({'state':1,categoryId}).populate('authorId','name').populate('categoryId').skip(min).limit(10).sort({updateAt:-1}).exec(function(err, doc){
     if(doc.length ==0){
      resolve(false)
     }else{
      data.list = JSON.parse(JSON.stringify(doc))
      data.list.forEach(item => {
          if(item.thumbnail==''){
            item.thumbnail = ['/public/img/p'+ Math.floor(Math.random()*(3-1+1)+1)+'.jpg']  //随机缩略图
          }
          item.content = dec(item.content.toString()) //获取文章描述
        }); 
       resolve(JSON.parse(JSON.stringify(data)))
     }  
   })
  })

}

//更新浏览量
blogAction.viewUP = function(_id){
  return new Promise(function(resolve,reject){
    model.article.findOneAndUpdate({_id},{ $inc: {'countInfo.visitCount': 1 }},{ new: true },function(err,doc){
      if(!err){
        //console.log('更新计数成功',doc)
      }
    })

  })
}

//获取焦点图 有图置顶的
blogAction.focusPic = function(start,limit){
  let focusPic
  return new Promise(function(resolve,reject){
    model.article.find({'state':1,thumbnail:{$ne:''},top:true}).populate('categoryId').skip(start).limit(limit).select({title:1,_id:1,thumbnail:1}).sort({updateAt:-1}).exec(function(err,doc){
      if(doc){
        focusPic =JSON.parse(JSON.stringify(doc)) 
      }else{
        focusPic =[]
      }
      resolve(JSON.parse(JSON.stringify(focusPic)))
    })
  })
}

//获取精华文章
blogAction.good = function(start,limit){
  let goods
  return new Promise(function(resolve,reject){
    model.article.find({'state':1,thumbnail:{$ne:''},good:true}).populate('categoryId').skip(start).limit(limit).select({title:1,_id:1,thumbnail:1}).sort({updateAt:-1}).exec(function(err,doc){
      if(doc){
        goods = doc
      }else{
        goods =[]
      }
      resolve(JSON.parse(JSON.stringify(goods)))
    })
  })
}

//首页20篇列表
blogAction.homeList= function(){
  return new Promise(function(resolve,reject){
    model.article.find({'state':1,good:{$ne:true},top:true}).populate('categoryId').skip(0).limit(20).sort({updateAt:-1}).exec(function(err,doc){
      if(doc){
        doc.forEach(item => {
          if(item.thumbnail==''){
            item.thumbnail = ['/public/img/p'+ Math.floor(Math.random()*(3-1+1)+1)+'.jpg']  //随机缩略图
          }
          item.content = dec(item.content.toString()) //获取文章描述
        });
        resolve(JSON.parse(JSON.stringify(doc)))
      }
    })
  })
}

//时间轴
blogAction.time= function(cateid,page){
  let data = {}
  let min= (page-1)*10;
  return new Promise(async function(resolve,reject){
    let categoryId
    await model.category.findOne({cateid},function(err,result){
      //console.log('objectid',result)
       categoryId = result._id
     })
     //分页
     await model.article.find({'state':1,categoryId}).count({}, (err, count) => {
      data.count=count
   })

     await model.article.find({'state':1,categoryId}).populate('authorId','name').populate('categoryId').select({title:1,_id:1,createAt:1}).sort({createAt:1}).exec(function(err, doc){
     if(doc.length ==0){
      resolve(false)
     }else{
      data.list = JSON.parse(JSON.stringify(doc))
      data.list.forEach(item => {
          if(item.thumbnail==''){
            item.thumbnail = ['/public/img/p'+ Math.floor(Math.random()*(3-1+1)+1)+'.jpg']  //随机缩略图
          }
         // item.content = dec(item.content.toString()) //获取文章描述
        }); 
       resolve(JSON.parse(JSON.stringify(data)))
     }  
   })
  })
}

//更新点赞
blogAction.digg = function(_id){
  return new Promise(function(resolve,reject){
    model.article.findOneAndUpdate({_id},{ $inc: {'countInfo.likeCount': 1 }},{ new: true }).exec(function(err,doc){
      resolve(doc)    
    })
  })
}

//获得点赞
blogAction.getdigg = function(_id){
  return new Promise(function(resolve,reject){
    model.article.findById(_id).exec(function(err,doc){
      resolve(doc.countInfo.likeCount)    
    })
  })
}

//搜索
blogAction.search = function(keyword,page){
  let data = {}
  let min= (page-1)*10;
  return new Promise(async function(resolve,reject){

     //分页
  await model.article.find({'state':1,
  $or:[{title: {$regex: keyword,$options: '$i'}},
     {content: {$regex: keyword, $options: '$i'}}, //  $options: '$i' 忽略大小写
   ]
}).count({}, (err, count) => {
      data.count=count
   })

   await model.article.find({'state':1,
      $or:[{'title': {$regex: keyword,$options: '$i'}},
         {'content': {$regex: keyword, $options: '$i'}}, //  $options: '$i' 忽略大小写
       ]
    }).populate('authorId','name').populate('categoryId').skip(min).limit(10).sort({createAt:-1}).exec(function(err,doc){
      data.list = JSON.parse(JSON.stringify(doc))
      data.list.forEach(item => {
        if(item.thumbnail==''){
          item.thumbnail = ['/public/img/p'+ Math.floor(Math.random()*(3-1+1)+1)+'.jpg']  //随机缩略图
        }
        item.content = dec(item.content.toString()) //获取文章描述
      }); 
      resolve(data)
    })
  })
}


//查询所有tag
blogAction.tagAll= function(){
  return new Promise(function(resolve,reject){
    model.tag.find({},function(err,doc){
      if(doc){
        let alltags = JSON.parse(JSON.stringify(doc))
        resolve(alltags)
      }
    })
  })
}

//根据标签获取文章列表
blogAction.blogByTag = function(_id,page){
  let data = {}
  let min= (page-1)*10;
  return new Promise(async function(resolve,reject){
     //分页
     await model.article.find({'state':1,'tags':{$in:[_id]}}).count({}, (err, count) => {
      data.count=count
   })

     await model.article.find({'state':1,'tags':{$in:[_id]}}).populate('authorId','name').populate('categoryId').skip(min).limit(10).sort({updateAt:-1}).exec(function(err, doc){
     if(doc.length ==0){
      resolve(false)
     }else{
      data.list = JSON.parse(JSON.stringify(doc))
      data.list.forEach(item => {
          if(item.thumbnail==''){
            item.thumbnail = ['/public/img/p'+ Math.floor(Math.random()*(3-1+1)+1)+'.jpg']  //随机缩略图
          }
          item.content = dec(item.content.toString()) //获取文章描述
        }); 
       resolve(JSON.parse(JSON.stringify(data)))
     }  
   })
  })

}



module.exports = blogAction